﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Press.MVC.Data;
using System.Web.Security;

namespace Press.MVC.Services
{
    public class DBUtilService : IDBUtilService
    {
        IDBUtil _repository = null;
        /// <summary>
        /// Creates a BlogService based on the passed-in repository
        /// </summary>
        /// <param name="repository">An IBlogRepository</param>
        public DBUtilService(IDBUtil repository)
        {
            _repository = repository;
            if (_repository == null)
                throw new InvalidOperationException("Repository cannot be null");
        }

        public void ReInstallDB()
        {
            _repository.DeleteDatabase();
            _repository.CreateDatabase();
        }

        public bool IsInstalled()
        {
            string errorMessage = "";
            return _repository.ValidateDatabaseConnection(out errorMessage);
        }

        public bool InstallDB()
        {
            bool dbCreatedSucessfully = false;

            // Create Press MVC Database specific tables
            string errorMessage = "";
            if (!_repository.ValidateDatabaseConnection(out errorMessage))
            {
                _repository.CreateDatabase();
                dbCreatedSucessfully = true;
            }

            // Install AspNet Membership tables/views/stored procedures
            //TODO more error checking. throw errors from data and service layers to send to the View for user.
            dbCreatedSucessfully = _repository.AspnetMembershipSQlScriptInstall();

            dbCreatedSucessfully = _repository.CreateAspNetApplication();

            Roles.CreateRole("MtaAdmin");
            Roles.CreateRole("BlogAdmin");

            // Install Sample Data
            dbCreatedSucessfully = _repository.SampleDataInstall();

            return dbCreatedSucessfully;
        }

        public bool CanVerifyDatabaseConnection(out string errorMessage)
        {
            //string errMsg = "";
            return _repository.ValidateDatabaseConnection(out errorMessage);
        }

        public string GetConnectionString()
        {
            string scon = _repository.GetConnectionString();
            return scon;
        }

        public bool UnInstallDatabase()
        {
            bool isUnInstallDatabaseSucessfull = false;
            string errorMessage = "";
            if (_repository.ValidateDatabaseConnection(out errorMessage))
            {
                _repository.DeleteDatabase();
                isUnInstallDatabaseSucessfull = true;
            }
            return isUnInstallDatabaseSucessfull;
        }
    }
}
